package com.anysoft.utils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.widget.Toast;

import com.anysoft.HostConstant;
import com.anysoft.MentorApplication;

import java.io.File;

/**
 * Created by lty on 2017/12/2.
 */

public class DownLoadHelper {

    private static final String DOWNLOAD_APK_NAME = "gy_new.apk";
    private static final String APK_DOWNLOAD_ID = "apkDownloadId";
    private static BroadcastReceiver completeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            long downloadId = PreferencesUtils.getLong(context, HostConstant.SP_NAME_UPDATE);
            if (completeDownloadId == downloadId) {

                if (queryDownloadStatus(downloadManager, downloadId) == DownloadManager.STATUS_SUCCESSFUL) {

                    PreferencesUtils.clearPreference(context);

                    //install apk
                    String apkFilePath = new StringBuilder(DiskUtils.DOWNLOAD_PATH).append(File.separator)
                            .append(DOWNLOAD_APK_NAME).toString();
                    install(context, apkFilePath);
                }
            }
        }
    };
    private static DownloadManager downloadManager;

    /**
     * 查询下载状态
     */
    public static int queryDownloadStatus(DownloadManager downloadManager, long downloadId) {
        int result = -1;
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = null;
        try {
            c = downloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                result = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return result;
    }

    /**
     * install app
     *
     * @param context
     * @param filePath
     * @return whether apk exist
     */
    public static boolean install(Context context, String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
            i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
            return true;
        }
        return false;
    }

    /**
     * 下载附件
     */
    public static void downloadFile(String url,String desc){
        File folder = new File(DiskUtils.DOWNLOAD_PATH);
        if (!folder.exists()|| !folder.isDirectory()){
            folder.mkdirs();
        }
        File apkFile = new File(folder,DOWNLOAD_APK_NAME);
        if (apkFile.exists()) {
            apkFile.delete();
        }
//       //取得系统的下载服务
        downloadManager = (DownloadManager) MentorApplication.context.getSystemService(Context
                .DOWNLOAD_SERVICE);
        //创建下载请求对象
        DownloadManager.Request request=new DownloadManager.Request(Uri.parse(url));
        request.setTitle("版本更新");
        request.setDescription(desc);
        request.setDestinationInExternalPublicDir(DiskUtils.DOWNLOAD_PATH,DOWNLOAD_APK_NAME);
        request.setNotificationVisibility(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        request.setShowRunningNotification(true);
        long downloadId = downloadManager.enqueue(request);
        PreferencesUtils.putLong(MentorApplication.context, HostConstant.SP_NAME_UPDATE, downloadId);
        Toast.makeText(MentorApplication.context,"开始下载请稍后...",Toast.LENGTH_SHORT).show();
        MentorApplication.context.registerReceiver(completeReceiver, new IntentFilter(DownloadManager
                .ACTION_DOWNLOAD_COMPLETE));

    }
}
